// pages/wallet/wallet.ts
import { MerchantAPI } from '../../utils/api'

interface Transaction {
  flowId: number;
  flowNo: string;
  flowType: number;  // 1-收入，2-支出
  businessType: number;
  businessName: string;
  amount: number;
  createdAt: string;
}

interface WalletPageData {
  statusBarHeight: number;
  balance: string;
  balanceValue: number;
  transactions: any[];
  loading: boolean;
  showWithdrawModal: boolean;
  withdrawAmount: string;
  withdrawRemark: string;
  bankCards: any[];
  selectedCardId: number;
}

Page({

  data: {
    statusBarHeight: 0,
    balance: '0.00',
    balanceValue: 0,
    transactions: [],
    loading: false,
    showWithdrawModal: false,
    withdrawAmount: '',
    withdrawRemark: '',
    bankCards: [],
    selectedCardId: 0
  } as WalletPageData,

  onLoad() {
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight || 0
    });
    
    this.loadWalletData();
    this.loadRecentTransactions();
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadWalletData();
    this.loadRecentTransactions();
  },

  /**
   * 加载钱包数据
   */
  async loadWalletData() {
    try {
      const response = await MerchantAPI.getFinanceBalance();
      
      if (response.code === 200 && response.data) {
        const balance = response.data.balance || 0;
        this.setData({
          balance: this.formatMoney(balance),
          balanceValue: balance
        });
      }
    } catch (error) {
      console.error('加载钱包数据失败:', error);
      // 失败时使用默认值
    }
  },

  /**
   * 加载最近交易记录
   */
  async loadRecentTransactions() {
    try {
      const response = await MerchantAPI.getFinanceFlowList({
        pageNum: 1,
        pageSize: 5
      });
      
      if (response.code === 200) {
        // 兼容不同的返回格式：data.list 或 rows
        const dataList = response.data?.list || response.rows || [];
        
        const transactions = dataList.map((item: Transaction) => {
          return {
            id: item.flowId,
            flowNo: item.flowNo,
            type: item.flowType === 1 ? 'income' : 'expense',
            title: item.businessName || (item.flowType === 1 ? '收入' : '支出'),
            time: item.createdAt,
            amount: (item.flowType === 1 ? '+' : '-') + '¥' + this.formatMoney(item.amount)
          };
        });
        
        this.setData({ transactions });
      }
    } catch (error) {
      console.error('加载交易记录失败:', error);
      // 失败时显示空列表
    }
  },

  /**
   * 格式化金额
   */
  formatMoney(amount: number): string {
    return amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  },

  goBack() {
    wx.navigateBack();
  },

  navigateTo(e: any) {
    const url = e.currentTarget.dataset.url;
    if (url) {
      wx.navigateTo({ url });
    }
  },

  /**
   * 显示提现弹窗
   */
  async showWithdrawModal() {
    // 先加载银行卡列表
    try {
      const response = await MerchantAPI.getBankCards();
      
      if (response.code === 200 && response.data) {
        const bankCards = response.data;
        
        if (bankCards.length === 0) {
          wx.showModal({
            title: '提示',
            content: '请先添加银行卡',
            confirmText: '去添加',
            success: (res) => {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/bank-card/bank-card'
                });
              }
            }
          });
          return;
        }
        
        this.setData({
          bankCards: bankCards,
          selectedCardId: bankCards[0].cardId || bankCards[0].id,
          showWithdrawModal: true
        });
      }
    } catch (error) {
      console.error('加载银行卡失败:', error);
      wx.showToast({
        title: '加载银行卡失败',
        icon: 'none'
      });
    }
  },

  /**
   * 关闭提现弹窗
   */
  closeWithdrawModal() {
    this.setData({
      showWithdrawModal: false,
      withdrawAmount: '',
      withdrawRemark: ''
    });
  },

  /**
   * 输入提现金额
   */
  onWithdrawAmountInput(e: any) {
    this.setData({
      withdrawAmount: e.detail.value
    });
  },

  /**
   * 输入提现备注
   */
  onWithdrawRemarkInput(e: any) {
    this.setData({
      withdrawRemark: e.detail.value
    });
  },

  /**
   * 选择银行卡
   */
  selectBankCard(e: any) {
    const cardId = e.currentTarget.dataset.cardId;
    this.setData({
      selectedCardId: cardId
    });
  },

  /**
   * 提交提现申请
   */
  async submitWithdraw() {
    const { withdrawAmount, selectedCardId, withdrawRemark, balanceValue } = this.data;
    
    // 验证提现金额
    if (!withdrawAmount || parseFloat(withdrawAmount) <= 0) {
      wx.showToast({
        title: '请输入提现金额',
        icon: 'none'
      });
      return;
    }
    
    const amount = parseFloat(withdrawAmount);
    
    // 验证余额
    if (amount > balanceValue) {
      wx.showToast({
        title: '余额不足',
        icon: 'none'
      });
      return;
    }
    
    // 验证银行卡
    if (!selectedCardId) {
      wx.showToast({
        title: '请选择银行卡',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({ title: '提交中...' });
    
    try {
      const response = await MerchantAPI.submitWithdraw({
        amount: amount,
        withdrawalCardId: selectedCardId,
        remark: withdrawRemark || ''
      });
      
      wx.hideLoading();
      
      if (response.code === 200) {
        wx.showToast({
          title: '提现申请已提交',
          icon: 'success'
        });
        
        // 关闭弹窗并刷新数据
        this.closeWithdrawModal();
        this.loadWalletData();
        this.loadRecentTransactions();
      } else {
        wx.showToast({
          title: response.msg || '提现申请失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('提现申请失败:', error);
      wx.showToast({
        title: '提现申请失败',
        icon: 'none'
      });
    }
  },

  /**
   * 快速填充金额
   */
  quickFillAmount(e: any) {
    const amount = e.currentTarget.dataset.amount;
    if (amount === 'all') {
      this.setData({
        withdrawAmount: this.data.balanceValue.toString()
      });
    } else {
      this.setData({
        withdrawAmount: amount
      });
    }
  },

  openSettings() {
    wx.navigateTo({
      url: '/pages/transaction/transaction'
    });
  },

  openHelp() {
    wx.showModal({
      title: '帮助中心',
      content: '提现功能说明：\n1. 最低提现金额100元\n2. 提现申请将在1-3个工作日内处理\n3. 提现到账时间根据银行不同略有差异',
      showCancel: false
    });
  }
});

